package com.jessechanrui.template.thread;

import java.util.concurrent.*;

/**
 * 创建线程方法
 *
 * @author chenrui
 * @date 2024/12/11
 */
public class CreatThreadCase {

    public static void main(String[] args) {
//        方式一：继承Thread
        new Thread1("方式一线程").start();

//        方式二：实现Runnable
        new Thread(new Thread2(), "方式二线程").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " 方式二：匿名内部类");
            }
        }).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 方式二：Lambda方式");
        }).start();

//        方式三：使用Callable和FutureTask
        FutureTask<String> futureTask = new FutureTask<>(new ReturnableTask());
        new Thread(futureTask, "方式三线程").start();
        try{
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() + " 线程执行期间主线程执行处理");
            String s = futureTask.get();
            System.out.println("异步返回内容：" + s);
        }catch (ExecutionException | InterruptedException e){
            e.printStackTrace();
        }


//        方式四：使用线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new Thread1("方式四线程"));
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " 方式四：匿名内部类");
            }
        });
        executorService.execute(() -> {
            System.out.println(Thread.currentThread().getName() + " 方式四：Lambda方式");
        });

        executorService.execute(new Thread2());

        Future submit = executorService.submit(new ReturnableTask());
        try {
            System.out.println("最终结果：" + submit.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        executorService.shutdown();
    }

    static class Thread1 extends Thread{
        public Thread1(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(getName() +  " 方式一：线程执行");
        }
    }

    static class Thread2 implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 方式二：线程执行");
        }
    }

    static class ReturnableTask implements Callable<String> {

        @Override
        public String call() throws Exception {
            //异步执行的具体逻辑
            //模拟异常处理时间
            System.out.println(Thread.currentThread().getName() + " 线程运行开始.");
            Thread.sleep(500);
            System.out.println(Thread.currentThread().getName() + " 线程运行结束.");
            return "异步返回结果";
        }
    }
}
